package com.hm.service.controller;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@RestController
@RequestMapping(value = "/MAIN", produces = {"multipart/form-data"})
public class WCPS_000_000_005 {
    private static final Logger logger = LoggerFactory.getLogger(WCPS_000_000_005.class);


    //文件上传
    @PostMapping(value = "/000_000_005")
    //参数名需要与form表单中设置的 name属性值对应上，否则获取到的为null
    public String doPost(MultipartFile file, HttpServletRequest req) {
        //验证permit
        String permit = req.getHeader("permit");
        if (permit == null || !permit.equals("123456789")) {
            return "验证失败！非法上传！";
        }
        //1、处理创建文件夹
        String folderPath = "D:/001/002";
        File folder = new File(folderPath);
        //不存在，则创建
        if (!folder.exists()) {
            boolean success = folder.mkdirs();
            if (success) {
                logger.error("创建文件夹成功：" + folderPath);
            } else {
                logger.error("文件夹创建失败：" + folderPath);
            }
        }
        //2、处理文件名
        if (file == null) {
            return "文件为空！";
        }
        String oldName = file.getOriginalFilename();
        //获取文件后缀名
        if (oldName == null) {
            return "oldName为空！";
        }
        int index = oldName.lastIndexOf(".");
        if (index > 0) {
            String suffixName = oldName.substring(index);
            logger.error("文件后缀名：" + suffixName);
            try {
                //文件保存
                String newName = UUID.randomUUID() + suffixName;
                file.transferTo(new File(folder, newName));
                return "上传成功" + newName;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        } else {
            logger.error("文件后缀名格式错误！");
            return "文件后缀名格式错误！";
        }
        return "-1";
    }


}
